﻿using Autofac;
using StarsAdmin.Core.Attributes;
using StarsAdmin.Core.Helpers;
using System.Reflection;
using Module = Autofac.Module;

namespace StarsAdmin.Web.Core.Modules
{
    /// <summary>
    /// 单例注入模块
    /// </summary>
    public class SingleInstanceModule : Module
    {
        public SingleInstanceModule()
        {
        }

        protected override void Load(ContainerBuilder builder)
        {
            string[] assemblieList = ["StarsAdmin.Application", "StarsAdmin.Core"];
            // 获得要注入的程序集
            Assembly[] assemblies = AssemblyHelper.GetAssemblyList(assemblieList);

            //无接口注入单例
            builder.RegisterAssemblyTypes(assemblies)
            .Where(t => t.GetCustomAttribute<SingleInstanceAttribute>(false) != null)
            .SingleInstance()
            .PropertiesAutowired();

            //有接口注入单例
            builder.RegisterAssemblyTypes(assemblies)
            .Where(t => t.GetCustomAttribute<SingleInstanceAttribute>(false) != null)
            .AsImplementedInterfaces()
            .SingleInstance()
            .PropertiesAutowired();

            base.Load(builder);
        }
    }
}